const jwt = require('jsonwebtoken');
const User = require('../models/User');
const { redisClient } = require('../config/redis');

const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';

exports.register = async (ctx) => {
  try {
    const { username, email, password } = ctx.request.body;
    
    const user = new User({ username, email, password });
    await user.save();
    
    const token = jwt.sign({ id: user._id }, JWT_SECRET);
    
    ctx.status = 201;
    ctx.body = { user, token };
  } catch (err) {
    ctx.status = 400;
    ctx.body = { error: err.message };
  }
};

exports.login = async (ctx) => {
  try {
    const { username, password } = ctx.request.body;
    
    // Try to get user from cache
    const cachedUser = await redisClient.get(`user:${username}`);
    let user;
    
    if (cachedUser) {
      user = JSON.parse(cachedUser);
    } else {
      user = await User.findOne({ username });
      // Cache user data for 1 hour
      await redisClient.setEx(`user:${username}`, 3600, JSON.stringify(user));
    }
    
    if (!user || !(await user.comparePassword(password))) {
      ctx.status = 401;
      ctx.body = { error: 'Invalid credentials' };
      return;
    }
    
    const token = jwt.sign({ id: user._id }, JWT_SECRET);
    
    ctx.body = { user, token };
  } catch (err) {
    ctx.status = 400;
    ctx.body = { error: err.message };
  }
};